package com.hunhjy.wx.action;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hunhjy.core.kit.HttpKit;
import com.hunhjy.wx.services.WechartServer;
import com.hunhjy.wx.wxsdk.api.ApiConfigKit;
import com.hunhjy.wx.wxsdk.util.MsgEncryptUtil;
import com.hunhjy.wx.wxsdk.util.SignatureCheckUtil;
import com.hunhjy.wx.wxsdk.vo.msg.InMsgParser;
import com.hunhjy.wx.wxsdk.vo.msg.in.InMsg;
import com.hunhjy.wx.wxsdk.vo.msg.out.OutMsg;
import com.hunhjy.wx.wxsdk.vo.msg.out.OutTextMsg;

/**
 * 微信消息action
 * 
 * @version 2016-3-22上午11:33:08
 */
@Controller
@RequestMapping("/wx")
public class WechartAction {

	// 日志记录
	private static Logger logger = LogManager.getLogger();
	@Resource
	private WechartServer wechartServer;

	// Request参数
	private Map<String, String[]> params;

	private HttpServletRequest req;

	private String inMsgXml = null; // 本次请求 xml数据
	private InMsg inMsg = null; // 本次请求 xml 解析后的 InMsg 对象

	/**
	 * 处理微信信息
	 */
	@RequestMapping(value = "/msg")
	@ResponseBody
	public String  msg(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		this.req = req;
		setParams(req.getParameterMap());
		String respmsg = "success";
		String method = req.getMethod();
		if ("get".equalsIgnoreCase(method)) {
			respmsg = SignatureCheckUtil.me.checkSignature(req);
		} else {
			// 调用核心业务类接收消息、处理消息
			// 解析消息并根据消息类型分发到相应的处理方法
			// respmsg = wechartServer.processInMsg(req);
			logger.debug("微信响应微信消息处理.OK!");
		}
//		resp.setCharacterEncoding("UTF-8");
//		resp.setContentType("text/html");
//		resp.getWriter().print(respmsg);
		return  respmsg;

	}

	/**
	 * 获取参数值
	 */
	private String getPara(String param) {
		String[] vals = params.get(param);
		return vals == null ? null : vals[0];
	}

	/**
	 * 设置微信服务器请求参数
	 */
	private void setParams(Map<String, String[]> params) {
		this.params = params;
		if (logger.isDebugEnabled()) {
			Set<Entry<String, String[]>> es = params.entrySet();
			logger.debug("微信服务器请求参数列表.");
			for (Entry<String, String[]> e : es) {
				logger.debug("{}-{}", e.getKey(), e.getValue()[0]);
			}
		}
	}

	/**
	 * : 从请求中截取xml内容，解析为InMsg对象
	 */
	private InMsg getInMsg() {
		if (inMsg == null) {
			inMsg = InMsgParser.parse(getInMsgXml());
		}
		return inMsg;
	}

	/**
	 * 从请求中截取xml内容，并判断是否需要解密
	 */
	private String getInMsgXml() {
		if (inMsgXml == null) {
			inMsgXml = HttpKit.readData(req);
			if (ApiConfigKit.getWxAccount().isEncryptMsg()) {
				// 是否需要解密消息
				inMsgXml = MsgEncryptUtil.decrypt(inMsgXml, getPara("timestamp"), getPara("nonce"),
						getPara("msg_signature"));
			}
			logger.debug(inMsgXml);
		}
		return inMsgXml;
	}

	@SuppressWarnings("unused")
	private String renderOutTextMsg(String content) {
		OutTextMsg outMsg = new OutTextMsg(getInMsg());
		outMsg.setContent(content);
		return render(outMsg);
	}

	/**
	 * 在接收到微信服务器的 InMsg 消息后后响应 OutMsg 消息
	 */
	private String render(OutMsg outMsg) {
		String outMsgXml = outMsg.toXml();
		// 开发模式向控制台输出即将发送的 OutMsg 消息的 xml 内容
		if (logger.isDebugEnabled()) {
			System.out.println("发送消息:");
			System.out.println(outMsgXml);
			System.out.println("--------------------------------------------------------------------------------\n");
		}

		if (ApiConfigKit.getWxAccount().isEncryptMsg()) {
			// 是否需要加密消息
			outMsgXml = MsgEncryptUtil.encrypt(outMsgXml, getPara("timestamp"), getPara("nonce"));
		}
		return outMsgXml;
	}
}
